
package com.ansion.utils;

import android.annotation.TargetApi;
import android.app.ActivityManager;
import android.content.Context;
import android.media.AudioManager;
import android.os.Build;
import android.os.VibrationEffect;
import android.os.Vibrator;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;

import com.ansion.log.VLog;

import java.io.File;
import java.io.FileFilter;
import java.util.regex.Pattern;


public class DevicesUtils {
    private static final String TAG = "DevicesUtils";

    private static String deviceDesc = null;

    public static String getDeviceDescription() {
        if (deviceDesc == null) {
            StringBuffer sb = new StringBuffer();
            sb.append('\n');
            sb.append('\t').append("Build.MANUFACTURER\t").append(Build.MANUFACTURER).append('\n');
            sb.append('\t').append("Build.MODEL\t").append(Build.MODEL).append('\n');
            sb.append('\t').append("Build.PRODUCT\t").append(Build.PRODUCT).append('\n');
            sb.append('\t').append("Build.DEVICE\t").append(Build.DEVICE).append('\n');
            sb.append('\t').append("Build.BOARD\t").append(Build.BOARD).append('\n');
            sb.append('\t').append("Build.BRAND\t").append(Build.BRAND).append('\n');
            sb.append('\t').append("Build.CPU_ABI\t").append(Build.CPU_ABI).append('\n');
            sb.append('\t').append("Build.DISPLAY\t").append(Build.DISPLAY).append('\n');
            sb.append('\t').append("Build.FINGERPRINT\t").append(Build.FINGERPRINT).append('\n');
            sb.append('\t').append("Build.HARDWARE\t").append(Build.HARDWARE).append('\n');
            sb.append('\t').append("Build.RADIO\t").append(Build.RADIO).append('\n');
            sb.append('\t').append("Build.SERIAL\t").append(getSN()).append('\n');
            sb.append('\t').append("Build.TAGS\t").append(Build.TAGS).append('\n');
            sb.append('\t').append("Build.TYPE\t").append(Build.TYPE).append('\n');
            sb.append('\t').append("Build.SDK_INT\t").append(Build.VERSION.SDK_INT).append('\n');
            deviceDesc = sb.toString();
        }

        return deviceDesc;
    }


    private static String sSerialNumber = null;
    @TargetApi(Build.VERSION_CODES.GINGERBREAD)
    public static String getSN() {
        if (TextUtils.isEmpty(sSerialNumber)) {
            try {
                sSerialNumber = Build.SERIAL;
            } catch (Exception e) {
                sSerialNumber = "Serial-Not-Available";
            }
        }

        return sSerialNumber;
    }


    public static int getCpuCoreNumber() {
        class CpuFilter implements FileFilter {
            @Override
            public boolean accept(File pathname) {
                // Check if filename is "cpu", followed by a single digit number
                if (Pattern.matches("cpu[0-9]", pathname.getName())) {
                    return true;
                }
                return false;
            }
        }

        try {
            // Get directory containing CPU info
            File dir = new File("/sys/devices/system/cpu/");
            // Filter to only list the devices we care about
            File[] files = dir.listFiles(new CpuFilter());
            // Return the number of cores (virtual CPU devices)
            return files.length;
        } catch (Exception e) {
            VLog.eonly(e);
        }
        return 1;
    }

    //获取电信运营商信息
    public static String getIMSI() {
        return "00000";
    }

    /**
     * Returns a constant indicating the device phone type.  This
     * indicates the type of radio used to transmit voice calls.
     */
    public static String getPhoneType() {
        String type = "NONE";
        TelephonyManager telManager = (TelephonyManager) ResourceUtils.getContext().getSystemService(Context.TELEPHONY_SERVICE);
        try {
            switch (telManager.getPhoneType()) {
                case TelephonyManager.PHONE_TYPE_NONE:
                    type = "NONE";
                    break;
                case TelephonyManager.PHONE_TYPE_GSM:
                    type = "GSM";
                    break;
                case TelephonyManager.PHONE_TYPE_CDMA:
                    type = "CDMA";
                    break;
                case TelephonyManager.PHONE_TYPE_SIP:
                    type = "SIP";
                    break;
            }
        } catch (Exception e) {

        }
        return type;
    }

    public static long getAvailMemory() {
        Context context = ResourceUtils.getContext();
        ActivityManager am = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
        am.getMemoryInfo(mi);
        return mi.availMem;
    }

    public static long getTotalMemory() {
        Context context = ResourceUtils.getContext();
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        ActivityManager.MemoryInfo memoryInfo = new ActivityManager.MemoryInfo();
        activityManager.getMemoryInfo(memoryInfo);
        return memoryInfo.totalMem;
    }

    public static boolean isLowEndDevice() {
        boolean isLowAndroidVersion = Build.VERSION.SDK_INT < Build.VERSION_CODES.M;
        long totalRam = getTotalMemory();
        boolean isLowMemory = totalRam <= 2L * 1024 * 1024 * 1024; // 2GB in bytes

        return isLowAndroidVersion && isLowMemory;
    }


    public static boolean isSlientMode() {
        AudioManager manager = (AudioManager) ResourceUtils.getContext()
                .getSystemService(Context.AUDIO_SERVICE);
        return manager.getRingerMode() == AudioManager.RINGER_MODE_SILENT;
    }

    public static boolean isVibrateMode() {
        AudioManager audioManager = (AudioManager) ResourceUtils.getContext()
                .getSystemService(Context.AUDIO_SERVICE);

        int vibrateEnable = 0;
        if(audioManager.getRingerMode()!= AudioManager.RINGER_MODE_SILENT){
            if(audioManager.getRingerMode()== AudioManager.RINGER_MODE_VIBRATE ||
                    audioManager.getRingerMode()== AudioManager.RINGER_MODE_NORMAL) {
                if (VLog.OPEN_LOG) {
                    VLog.i(TAG, "振动模式");
                }
                vibrateEnable = vibrateEnable | 1;
            } else {
                if (VLog.OPEN_LOG) {
                    VLog.i(TAG, "非静音，不振动");
                }
            }
        }

        if(audioManager.getStreamVolume(AudioManager.STREAM_RING) != 0) { // 音量不为0
            if(Build.VERSION.SDK_INT<= Build.VERSION_CODES.LOLLIPOP_MR1) {
                if(audioManager.getVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER)== AudioManager.VIBRATE_SETTING_ON
                        || audioManager.getVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER)== AudioManager.VIBRATE_SETTING_ONLY_SILENT){
                    if (VLog.OPEN_LOG) {
                        VLog.i(TAG, "version <= 23, 振动模式");
                    }
                    vibrateEnable = vibrateEnable | 1;
                }
            }
            if((1 == Settings.System.getInt(ResourceUtils.getContext().getContentResolver(), Settings.System.VIBRATE_WHEN_RINGING, 0))){
                if (VLog.OPEN_LOG) {
                    VLog.i(TAG, "VIBRATE_WHEN_RINGING 振动模式");
                }
                vibrateEnable = vibrateEnable | 1;
            }
        }
        if (VLog.OPEN_LOG) {
            VLog.e(TAG, "system.setting vibrateEnable = " + (vibrateEnable == 1));
        }
        return vibrateEnable == 1;
    }

    public static void vibrate(Context context){
        vibrate(context,200);
    }

    public static void vibrate(Context context, long milliseconds){
        Vibrator v = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            v.vibrate(VibrationEffect.createOneShot(milliseconds, VibrationEffect.DEFAULT_AMPLITUDE));
        } else {
            v.vibrate(milliseconds);
        }
    }
}
